package xyz.ljcc.ccmt.service.impl.admin;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import xyz.ljcc.ccmt.commons.utils.UpdateTool;
import xyz.ljcc.ccmt.model.base.Operation;
import xyz.ljcc.ccmt.repository.admin.OperationRepository;
import xyz.ljcc.ccmt.service.api.admin.OperationService;

@Service
public class OperationServiceImpl implements OperationService {

	@Autowired
	OperationRepository operationRepository;
	
	@Override
	public List<Operation> loadOperationsByLoginName(String loginName) {
		return operationRepository.loadByLoginName(loginName);
	}

	@Override
	public List<Operation> loadOperationsByParentId(Integer parentOperationId) {
		return operationRepository.getByParentOperationIdOrderBySortIndex(parentOperationId);
	}

	@Override
	public List<Operation> loadParentOperations() {
		return operationRepository.loadParentModule();
	}

	@Override
	public Operation getOperationById(Integer operationId) {
		return operationRepository.findOne(operationId);
	}

	@Override
	public Operation addOperation(Operation operation) {
		operation.setCreateTime(new Date());
		operation.setActive(1); // 默认启用
		if(operation.getParentOperationId() == null) {
			operation.setParentOperationId(-1);
		}else {
			if(operation.getSortIndex() == null)
				operation.setSortIndex(0);
			if(operation.getDeptShow() == null)
				operation.setDeptShow(1);
			if(operation.getPatShow() == null)
				operation.setPatShow(1);
		}
		return operationRepository.save(operation);
	}

	@Override
	public Operation editOperation(Operation operation) {
		Operation operation1 = operationRepository.findOne(operation.getOperationId());
		UpdateTool.copyNullProperties(operation1, operation);
		operation.setUpdateTime(new Date());
		return operationRepository.save(operation);
	}

	@Override
	public void delOperation(Integer operationId) {
		operationRepository.delete(operationId);
	}

	@Override
	public void activeOperation(Integer operationId, Integer active) {
		operationRepository.updateByHql("update Operation m set m.active = ?1 where m.operationId = ?2"
				, active
				, operationId); 
	}

	@Override
	public List<Operation> loadOperations() {
		return  operationRepository.findAll(new Sort("sortIndex"));
	}

}
